/*
 * Copyright 2017 JessYan
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package me.jessyan.mvparms.demo.mvp.ui.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatDelegate;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;

import com.jess.arms.R;
import com.jess.arms.base.delegate.IFragment;
import com.jess.arms.integration.cache.Cache;
import com.jess.arms.integration.cache.CacheType;
import com.jess.arms.integration.lifecycle.FragmentLifecycleable;
import com.jess.arms.mvp.IPresenter;
import com.jess.arms.utils.ArmsUtils;
import com.jess.arms.utils.PerfectClickListener;
import com.trello.rxlifecycle2.android.FragmentEvent;

import javax.inject.Inject;

import io.reactivex.subjects.BehaviorSubject;
import io.reactivex.subjects.Subject;

/**
  *  一级页面的basefragment
 * ================================================
 */
public abstract class OneLevelBaseFragment<P extends IPresenter> extends Fragment implements IFragment, FragmentLifecycleable {


    protected final String TAG = this.getClass().getSimpleName();
    private final BehaviorSubject<FragmentEvent> mLifecycleSubject = BehaviorSubject.create();
    private Cache<String, Object> mCache;
    protected Context mContext;

    //总
    protected RelativeLayout mContainer;
    //加载失败了
    private View mError;
    //内容
    private View mContent;
    //加载中
    protected View mLoading;

    protected boolean isVisible = false;


    @Inject
    @Nullable
    protected P mPresenter;//如果当前页面逻辑简单, Presenter 可以为 null

    @NonNull
    @Override
    public synchronized Cache<String, Object> provideCache() {
        if (mCache == null) {
            mCache = ArmsUtils.obtainAppComponentFromContext(getActivity()).cacheFactory().build(CacheType.FRAGMENT_CACHE);
        }
        return mCache;
    }

    @NonNull
    @Override
    public final Subject<FragmentEvent> provideLifecycleSubject() {
        return mLifecycleSubject;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        mContext = context;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        //dataBindIng初始化，
        View ll = inflater.inflate(R.layout.fragment_base, null);
        //找到contentView 的载体,
        mContainer = (RelativeLayout) ll.findViewById(R.id.container);
        mError =   ll.findViewById(R.id.fragment_error_vs);
        //初始化真正的布局
        mContent = initView(inflater, container, savedInstanceState);
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        mContent.setLayoutParams(params);
        //添加布局到载体里面
        mContainer.addView(mContent);
        //返回真正布局的载体的父布局
        return ll;
    }
    /**
     * 类似findId
     */
    protected <T extends View> T getView(int id) {
        return (T) getView().findViewById(id);
    }

    /**
     * 网络状态回调
     */
    public   void onReceiveBack(){

    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
    this.isVisible = isVisibleToUser;
    }

    /**
     * 加载失败点击重新加载的状态
     */
    protected void showFragmentError() {

        if (mLoading != null && mLoading.getVisibility() != View.GONE) {
            mLoading.setVisibility(View.GONE);
        }

        if (mError.getVisibility() != View.VISIBLE) {
            mError.setVisibility(View.VISIBLE);
        }
        if (mContent.getVisibility() != View.GONE) {
            mContent.setVisibility(View.GONE);
        }
    }

    /**
     * 加载完成的状态
     */
    protected void showFragementContentView() {
        if (mLoading != null && mLoading.getVisibility() != View.GONE) {
            mLoading.setVisibility(View.GONE);
        }
        mLoading.setVisibility(View.GONE);
        if (mError != null && mError.getVisibility() != View.GONE) {
            mError.setVisibility(View.GONE);
        }
        if (mContent.getVisibility() != View.VISIBLE) {
            mContent.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 显示加载中状态
     */
    protected void showFragementLoading() {
        if (mLoading != null && mLoading.getVisibility() != View.VISIBLE) {
            mLoading.setVisibility(View.VISIBLE);
        }
        mLoading.setVisibility(View.VISIBLE);
        if (mContent.getVisibility() != View.GONE) {
            mContent.setVisibility(View.GONE);
        }
        if (mError != null && mError.getVisibility() != View.GONE) {
            mError.setVisibility(View.GONE);
        }
    }


    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mLoading = getView(R.id.vs_loading);
        //初始加载按钮
        mContent.setVisibility(View.VISIBLE);
        //隐藏内容
        mLoading.setVisibility(View.GONE);

        // 点击加载失败布局
        mError.setOnClickListener(new PerfectClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {
                showFragementLoading();
                onRefresh();
            }
        });
        getView(R.id.base_fragment_to_setting).setOnClickListener(new PerfectClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {
                if(getActivity()!=null){
                Intent intent =  new Intent(Settings.ACTION_SETTINGS);
                getActivity().startActivity(intent);
                }
            }
        });
    }

    protected   void onRefresh(){

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mPresenter != null) mPresenter.onDestroy();//释放资源
        this.mPresenter = null;
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mContext = null;
    }

    /**
     * 是否使用 EventBus
     * Arms 核心库现在并不会依赖某个 EventBus, 要想使用 EventBus, 还请在项目中自行依赖对应的 EventBus
     * 现在支持两种 EventBus, greenrobot 的 EventBus 和畅销书 《Android源码设计模式解析与实战》的作者 何红辉 所作的 AndroidEventBus
     * 确保依赖后, 将此方法返回 true, Arms 会自动检测您依赖的 EventBus, 并自动注册
     * 这种做法可以让使用者有自行选择三方库的权利, 并且还可以减轻 Arms 的体积
     *
     * @return 返回 {@code true} (默认为使用 {@code true}), Arms 会自动注册 EventBus
     */
    @Override
    public boolean useEventBus() {
        return true;
    }

}
